# -*- coding: utf-8 -*-
from datetime import timedelta, datetime

from django import forms

from google.appengine.ext.db import djangoforms
from base.models import OneClass, Booth
from base.util.decorators import render_to, login_required, ajax_request
from base.util import JSONMsg
import logging

def _day_schedule(aday):
    query = OneClass.gql('WHERE date=:1 ORDER BY start_time', aday)
    return query.fetch(1000)

def _all_booth():
    booths = Booth.all()
    return [booth.number for booth in booths]

def get_week(aday):
    monday = aday - timedelta(aday.weekday())
    return [monday+timedelta(d) for d in range(0,6)]

@login_required
@render_to('schedule/week_schedule.html')
def week_schedule(request, year, month, day):
    aday = datetime(int(year), int(month), int(day))
    week = get_week(aday)
    result = {}
    for i, aday in enumerate(week):
        result[str(i)] = [aday, _day_schedule(aday)]
    return {'result': result}

@login_required
@render_to('schedule/day_schedule.html')
def day_schedule(request, year, month, day):
    aday = datetime(int(year), int(month), int(day))
    next_day = aday + timedelta(1)
    pre_day = aday - timedelta(1)
    oneclasses = _day_schedule(aday)
    booths = _all_booth()
    return {
        'oneclasses': oneclasses,
        'booths': booths,
        'next_day': next_day,
        'pre_day': pre_day,
        }

@ajax_request
def booth_set(request):
#    if request.is_ajax() == False:
#        return
    data = request.POST.copy()
    class_id = data.get('class', '').strip()
    booth_id = data.get('booth', '').strip()
    query = Booth.gql('WHERE number=:1', int(booth_id))
    booth = query.fetch(1)[0]
    oneclass = OneClass.get_using_id(int(class_id))
    result = JSONMsg()
    if oneclass == None:# or booth == None:
        result.failure('Error : NO CLASS')
        return result
    if booth == None:
        result.failure('Error : NO BOOTH')
        return result
    msg = booth.is_available(oneclass)
    logging.info(msg)
    if msg:
        result.failure(msg)
        return result
    oneclass.booth = booth
    oneclass.put()
    result.success('Good')
    return result

@ajax_request
def cancel_class(request):
#    if request.is_ajax() == False:
#        return
    data = request.POST.copy()
    class_id = data.get('class', '').strip()
    cancel_on = data.get('cancel', '').strip()
    logging.info(cancel_on)
    logging.info(type(cancel_on))

    oneclass = OneClass.get_using_id(int(class_id))
    result = JSONMsg()
    if oneclass == None:# or booth == None:
        result.failure('Error : NO CLASS')
        return result
    if cancel_on == 'ture':
        oneclass.status = 'cancel'
    else:
        oneclass.status = 'prepare'

    oneclass.put()
    result.success('Good')
    return result
